import Mock from 'mockjs';
import axios from 'axios';

// 用户数据
let users = [];
getUsers();

function getUsers() {
  users = sessionStorage.getItem('users');
  users = (users && JSON.parse(users)) || [];
  if (users.findIndex(user => user.username === "admin") < 0) {
    users.push({
      id: Mock.mock('@id'),
      username: 'admin',
      password: '123456',
      phoneNumber: '18502876757'
    });
    saveUsers();
  }
  if (users && users.length > 0) {
    for (let i = 0; i < users.length; i++) {
      users[i].sms = "";
    }
  }
}

function saveUsers() {
  for (let i = 0; i < users.length; i++) {
    users[i].sms && delete users[i].sms;
  }
  sessionStorage.setItem('users', JSON.stringify(users));
}

// 请求发送手机验证码
Mock.mock(/\/mock\/login\/sms/, 'post', req => {
  let user = JSON.parse(req.body);
  if (!user) return {
    status: 400,
    message: '获取验证码失败'
  }
  let item = users.find(item => item.phoneNumber === user.phoneNumber);
  if (item) {
    user = item;
  } else {
    users.push(user);
    user.id = Mock.mock('@id');
  }
  let smsCode = "";
  for (let i = 0; i < 6; i++) {
    smsCode += Mock.Random.character('number');
  }
  user.sms = smsCode;
  /* let sms_url = `http://utf8.api.smschinese.cn/?Uid=sunshine33&Key=d41d8cd98f00b204e980&smsMob=${user.phoneNumber}&smsText=【验证码】验证码:${user.sms}`;
  console.log(sms_url); */

  setTimeout(() => {
    saveUsers();
  }, 1000 * 60 * 5);
  return {
    status: 200,
    message: '获取验证码成功',
    code: user.sms
  }

  /* axios.post({
      url: sms_url,
      header: {
        'Access-Control-Allow-Origin': 'true'
      }
    })
    .then(function (ret) {
      setTimeout(() => {
        saveUsers();
      }, 1000 * 60 * 5);
      return {
        status: 200,
        message: '获取验证码成功'
      }
    })
    .catch(err => {
      setTimeout(() => {
        saveUsers();
      }, 1000 * 60 * 5);
      return {
        status: 200,
        message: '获取验证码成功',
        code: user.sms
      }
    }) */
});

Mock.mock(/\/mock\/login/, 'post', req => {
  let isSuccess = false;
  const loginInfo = JSON.parse(req.body);
  if (loginInfo.isPhoneLogin) {
    const user = users.find(item => item.phoneNumber === loginInfo.phoneNumber);
    isSuccess = user && user.sms === loginInfo.sms;
  } else {
    const user = users.find(item => item.username === loginInfo.username);
    isSuccess = user && loginInfo.password === user.password;
  }
  if (isSuccess) {
    sessionStorage.setItem('token', Mock.mock("id"));
    return {
      status: 200,
      message: '登录成功'
    }
  } else {
    sessionStorage.removeItem('token');
    return {
      status: 400,
      message: '登录失败'
    }
  }
});

Mock.mock(/\/mock\/logout/, 'get', req => {
  sessionStorage.removeItem('token');
  return {
    status: 200,
    message: '退出成功'
  }
});
